package cn.lijiajia3515.cairo.auth.framework.security.oauth2.server.authorization.jackson2;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.oauth2.core.AuthorizationGrantType;

import java.io.IOException;

public class AuthorizationGrantTypeDeserializer extends JsonDeserializer<AuthorizationGrantType> {

	@Override
	public AuthorizationGrantType deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectMapper mapper = (ObjectMapper) parser.getCodec();
		JsonNode root = mapper.readTree(parser);

		String value = JsonNodeUtils.findStringValue(root, "value");
		if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) {
			return AuthorizationGrantType.AUTHORIZATION_CODE;
		}
		if (AuthorizationGrantType.IMPLICIT.getValue().equalsIgnoreCase(value)) {
			return AuthorizationGrantType.IMPLICIT;
		}
		if (AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equalsIgnoreCase(value)) {
			return AuthorizationGrantType.CLIENT_CREDENTIALS;
		}
		if (AuthorizationGrantType.PASSWORD.getValue().equalsIgnoreCase(value)) {
			return AuthorizationGrantType.PASSWORD;
		}
		return null;
	}
}
